import uuid
from django.db.models import Q, F
from django.shortcuts import render
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.template import loader
from django.views import View
import requests
import hashlib
# 导入原生sql模块
from django.db import connection
import json

from rest_framework.response import Response
from rest_framework.views import APIView
from mydjango import settings
import os
import random
from PIL import ImageDraw
from PIL import ImageFont
from PIL import Image
import io
import time
import re
from django.shortcuts import render, HttpResponse  # 引入HttpResponse
from dwebsocket.decorators import accept_websocket  # 引入dwbsocket的accept_websocket装饰器
from userapp.tasks import *
import redis
import jwt
# 导入Q,F
from django.db.models import Q, F

from .models import CourseTags,Course,Chapter,CourseType
from .ser import CourseTags_Ser,Course_Ser,Path_Ser,Path_Stage_Ser,Chapter_Ser,CourseType_Ser
#导入路径类
from .models import Path,Path_Stage


from rest_framework_jwt.settings import api_settings

#建立redis连接
r = redis.Redis(host=settings.redis_host,port=settings.redis_port,password=settings.redis_password)
from mydjango.settings import UPLOAD_ROOT


# 所有标签tags
class Course_Tags(APIView):
    def get(self, request):
        all_tags = CourseTags.objects.all()
        course_data = CourseTags_Ser(instance=all_tags, many=True).data
        return Response({
            'data':course_data
        })


# 添加课程
class AddCourse(APIView):
    def post(self, request):
        data = request.data
        print(data)
        course_data = Course_Ser(data=data, many=True)
        if course_data.is_valid():
            course_data.save()
            return Response({
                'code':200,
                'message':'添加成功'
            })
        else:
            return Response({
                'code': 401,
                'message': '添加失败'
            })


#课程添加(正常入库)
class AddCourse_one(APIView):
    def post(self,request):
        title = request.data.get('title',None)
        desc = request.data.get('desc', None)
        author = request.data.get('author', None)
        price = request.data.get('price', None)
        pic = request.data.get('pic', None)
        type = request.data.get('type', None)
        tags_id = request.data.get('tags_id', None)

        course = Course.objects.filter(title=title).first()
        if course:
            res = {}
            res['code'] = 405
            res['message'] = "重复,拒绝"

            return Response(res)
        else:
            course = Course(title=title,desc=desc,author=author,price=price,is_online=0,pic=pic,flow=0,read=0,type=int(type),tags_id=int(tags_id))
            course.save()
            res = {}
            res['code'] = 200
            res['message'] = "添加成功"

            return Response(res)




class Add_img(APIView):
    def post(self,request):
        #接收参数
        img = request.FILES.get('file', None)
        #建立文件流对象
        f = open(os.path.join(UPLOAD_ROOT,'',img.name),'wb')
        #写入服务器端
        for chunk in img.chunks():
            f.write(chunk)
        f.close()

        # 返回文件名
        return HttpResponse(json.dumps({'filename': img.name}, ensure_ascii=False),content_type='application/json')

# 查看过滤课程数据
class Add_Path(APIView):
    def get(self,request):
        path_name = request.GET.get("path_name",None)
        desc = request.GET.get('desc',None)
        img = request.GET.get('img',None)

        path = Path.objects.filter(path=path_name).first()
        if path:
            res = {}
            res['code'] = 405
            res['message'] = "该路径已存在,请勿重复添加"

            return Response(res)
        else:
            Path(path=path_name,course_num=0,desc=desc,complete_num=0,img=img).save()
            res = {}
            res['code'] = 200
            res['message'] = "路径添加成功,请前往<阶段编辑>添加阶段信息"

            return Response(res)

#路径展示接口
class PathInfo(APIView):
    def get(self,request):
        id = request.GET.get('id',None)
        if id == None:
            path = Path.objects.filter()
            path_ser = Path_Ser(path,many=True)

            res = {}
            res['code'] = 200
            res['data'] = path_ser.data

            return Response(res)
        else:
            #查询路径详情
            path = Path.objects.filter(id=id)
            path_ser = Path_Ser(path,many=True)

            #查询阶段详情
            path_stage = Path_Stage.objects.filter(path_id=id)
            path_stage_ser = Path_Stage_Ser(path_stage, many=True)

            res = {}
            res['code'] = 200
            res['data'] = path_ser.data
            res['pathstage'] = path_stage_ser.data

            return Response(res)


#添加阶段
class Add_Stage(APIView):
    def get(self,request):
        stage = request.GET.get('stage',None)
        path_id = int(request.GET.get("path_id", None))

        #排重
        path_stage = Path_Stage.objects.filter(stage=stage).first()
        if path_stage:
            res = {}
            res['code'] = 405
            res['message'] = "该阶段已存在,请勿重复添加"

            return Response(res)
        else:
            Path_Stage(stage=stage,path_id=path_id).save()
            res = {}
            res['code'] = 200
            res['message'] = "阶段添加成功,请刷新页面查看"

            return Response(res)
# 查看课程
class Course_list(APIView):
    def get(self,request):
        # 当前页
        page = int(request.GET.get("page", 1))
        # 一页有多少条商品
        size = int(request.GET.get("size", 3))
        # 定义从哪开始切
        data_start = (page - 1) * size
        # 定义切到哪
        data_end = page * size
        # 查询数据
        course = Course.objects.all()[data_start:data_end]
        # 查询总数
        count = Course.objects.count()
        # 序列化操作
        course_list = Course_Ser(course, many=True).data
        res = {}
        res['code'] = 200
        res['total'] = count
        res['data'] = course_list
        return Response(res)

# 上线课程
class Course_online(APIView):
    def get(self,request):
        id = request.GET.get('id')
        course = Course.objects.filter(id=id).first()
        if course:
            course.is_online = 1
            course.save()
        res = {}
        res['code'] = 200
        res['msg'] = '上线成功'
        return Response(res)

#批量上线
class More_online(APIView):
    def get(self,request):
        # 批量上线
        ids = request.GET.get("ids", None)
        # 强转
        id_list = eval(ids)

        for i in id_list:
            course = Course.objects.filter(id=i).first()
            course.is_online = 1
            course.save()

        message = "批量上线成功"
        return Response({'message': message})


# 获取章节信息
class Chapter_info(APIView):
    def get(self, request):
        id = request.GET.get('id')
        # 查询数据
        chapter = Chapter.objects.filter(couse_id=id)
        # 序列化操作
        chapter_list = Chapter_Ser(chapter, many=True).data
        res = {}
        res['code'] = 200
        res['data'] = chapter_list
        return Response(res)
    def delete(self, request):
        id = request.data.get('id')
        chapter = Chapter.objects.filter(id=id).first()
        chapter.delete()
        res = {}
        res['code'] = 200
        res['msg'] = '删除成功'
        return Response(res)


# 添加章节
class AddChapter(APIView):
    def post(self, request):
        # 接收参数
        # 课程id
        course_id = request.POST.get("course_id", None)
        chapter_name = request.POST.get("chapter_name", None)
        file = request.FILES.get("file")
        f = open(os.path.join(UPLOAD_ROOT, '', str(file.name).replace('""','')), 'wb')
        for chunk in file.chunks():
            f.write(chunk)
        f.close()
        print(str(file.name))

        try:
            # 添加到数据库
            is_course = Chapter(course_id=str(course_id), chapter_name=chapter_name, video_content=str(file.name))
            is_course.save()
            return Response({
                'code':200,
                'message':'添加成功'
            })
        except:
            return Response({
                'code':401,
                'message':'添加失败'
            })


# 查看过滤课程数据
class FindCourse(APIView):
    def get(self,request):
        # print("123")
        print(request.GET)

        type_id = request.data("type_id",None)
        tags_id = request.data("tags_id",None)
        if type_id==None and tags_id==None:
            allcourse = Course.objects.all()
            # 序列化展示
            course_data = Course_Ser(instance=allcourse, many=True).data
            return Response({
                'code':200,
                'data':course_data
            })
        elif type_id:
            course = Course.objects.filter(type=type_id).all()
            course_data = Course_Ser(instance=course, many=True).data
            return Response({
                'code': 200,
                'data': course_data,
            })
        elif tags_id:
            course = Course.objects.filter(tags_id=tags_id).all()
            course_data = Course_Ser(instance=course, many=True).data
            return Response({
                'code': 200,
                'data': course_data,
            })
        else:
            course = Course.objects.filter(type=type_id,tags_id=tags_id).all()
            course_data = Course_Ser(instance=course, many=True).data
            return Response({
                'code': 200,
                'data': course_data,
            })



# 展示课程类别
class AllCourseType(APIView):
    def get(self, request):
        coursetype = CourseType.objects.all()
        # 序列化展示
        is_coursetype = CourseType_Ser(instance=coursetype, many=True).data
        return Response({
            'code':200,
            'data':is_coursetype
        })





# 添加标签
class AddTags(APIView):
    def get(self, request):
        course_tags = request.GET.get("course_tags", None)
        try:
            is_tags = CourseTags(course_tags=course_tags)
            is_tags.save()
            return Response({
                'code':200,
                'message':'添加成功'
            })
        except:
            return Response({
                'code':401,
                'message':'添加失败'
            })

# 查看所有标签
class AllTags(APIView):
    def get(self, reqeust):
        tags = CourseTags.objects.all()
        # 序列化展示
        tags_data = CourseTags_Ser(instance=tags, many=True).data
        return Response({
            'code':200,
            'data':tags_data
        })

# 修改标签
class UpdateTags(APIView):
    def get(self, request):
        tags_name1 = request.GET.get("course_tags1", None)
        tags_name2 = request.GET.get("course_tags2", None)
        try:
            is_tags = CourseTags.objects.filter(Q(course_tags=tags_name1)).update(course_tags=tags_name2)
            is_tags.save()
            return Response({
                'code': 200,
                'message': '修改成功'
            })
        except:
            return Response({
                'code': 401,
                'message': '修改失败'
            })


# 删除标签
class DeleteTags(APIView):
    def get(self, request):
        tid = request.GET.get("tag_id", None)
        CourseTags.objects.filter(id=tid).delete()
        return Response({
            'code':200,
            'message':'删除成功'
        })


# 修改课程分类
class Update_type(APIView):
    def post(self,request):
        type_id = request.data.get('type_id')
        id = request.data.get('id')
        # print(type_id,id)
        course = Course.objects.filter(id=id).first()
        course.type = type_id
        course.save()
        res = {}
        res['code'] = 200
        res['message'] = '修改成功'
        return Response(res)
#获取标签信息
class GetTags(APIView):
    def get(self,request):
        coursetags = CourseTags.objects.filter()
        coursetags_ser = CourseTags_Ser(coursetags,many=True)

        res = {}
        res['data'] = coursetags_ser.data

        return Response(res)


# 查看课程(添加章节使用)
class Course_list_chapter(APIView):
    def get(self,request):
        # 查询数据
        course = Course.objects.all()
        # 序列化操作
        course_list = Course_Ser(course, many=True).data
        res = {}
        res['code'] = 200
        res['data'] = course_list
        return Response(res)

#添加章节
class AddChapter_one(APIView):
    def get(self,request):
        couse_id = request.GET.get('couse_id', None)
        chapter_name = request.GET.get('chapter_name', None)
        video_content = request.GET.get('video_content', None)
        section = request.GET.get('section', None)

        if (couse_id,chapter_name,video_content,section) != None:
            chapter = Chapter(couse_id=couse_id, chapter_name=chapter_name, video_content=video_content, section=section)
            chapter.save()
            res = {}
            res['code'] = 200
            res['message'] = "添加成功"

            return Response(res)
        else:
            res = {}
            res['code'] = 405
            res['message'] = "拒绝"

            return Response(res)

# 对结果集美化方法
def dictfetchall(cursor):
    # 获取游标描述
    desc = cursor.description
    return [
        dict(zip([col[0] for col in desc], row))
        for row in cursor.fetchall()
    ]


class HotPath(View):
    def get(self, request):
        # 建立游标对象
        cursor = connection.cursor()
        # 执行sql语句
        cursor.execute(
            'select a.id,a.path,a.img from path as a order by complete_num desc limit 5 '
        )
        # 获取结果
        result = dictfetchall(cursor)
        # 返回结果 手动序列化
        return HttpResponse(json.dumps(result, ensure_ascii=False, indent=4, default=str),
                            content_type='application/json')


